import { isReferee } from "@/func";
import { WereWolfPickNumberState } from "@/werewolf/pickNumberState/state";
import { ButtonPushAfterEvent, Player } from "@minecraft/server";
import { Game, GameComponent } from "@sapi-game/main";
import { ScriptRunner } from "@sapi-game/Runner/scriptRunner";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";

export class PickNumberCampView extends GameComponent<WereWolfPickNumberState> {
    isCountingDown: boolean = false;

    override onAttach(): void {
        this.subscribe(Game.events.buttonPush, this.startButton.bind(this), {
            dimensionId: DimensionIds.Overworld,
            loc: [-181, -28, -131],
            sourceType: EntityTypeIds.Player,
        });
    }

    startButton(t: ButtonPushAfterEvent) {
        const p = t.source as Player;
        if (!isReferee(p)) {
            p.sendMessage("你不是裁判，无法开始游戏");
        } else {
            if (this.isCountingDown) {
                return p.sendMessage("不要重复开始游戏");
            }
            if (!this.state.checkPlayers()) {
                return this.context.players.title("人数过少，无法开始");
            }
            this.runner.run(this.startCountDown.bind(this));
        }
    }

    async startCountDown(r: ScriptRunner) {
        this.isCountingDown = true;
        const players = this.context.players;
        for (let i = 10; i > 0; i--) {
            players.actionbar(this.buildText(i));
            players.playSound("random.click");
            await r.wait(20);
        }
        const ans = this.state.start();
        if (!ans) this.isCountingDown = false;
    }

    buildText(time: number) {
        let color = "§a";
        if (time <= 3) {
            color = "§c";
        } else if (time <= 6) {
            color = "§e";
        }
        const bars = "｜".repeat(time);
        return `${color}§l${bars}§r§l ${time} ${color}${bars}`;
    }
}
